import { reactive } from "vue";
import { genFileId } from "element-plus";
import router from "@/router/index";
import { add, update, getById } from "@/api/health";
import { ElMessage } from "element-plus";

const uploadServerUrl = `${import.meta.env.VITE_API_SERVER}`;
export const $refs = reactive([]);

export const _$ = reactive({
  requestParam: {
    id: null,
  },
  headers: {
    Authorization: `Bearer ${localStorage.getItem("ats-user-token")}`,
  },
  fileList: [],
  responseParam: {},
  rules: reactive({}),
});

export const $ = {
  init(refs) {
    if (refs) {
      $refs.length = 0;
      refs.forEach((ref) => {
        $refs.push(ref);
      });
    }
  },

  async onSubmit(formEl) {
    if (!formEl) {
      return;
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        if (router.currentRoute.value.query.id) {
          update(_$.requestParam)
            .then((_) => {
              ElMessage({
                message: "修改成功",
                type: "success",
              });
            })
            .then((_) => {
              router.push("/manage/health");
            });
        } else {
          add(_$.requestParam)
            .then((_) => {
              ElMessage({
                message: "新增成功",
                type: "success",
              });
            })
            .then((_) => {
              router.push("/manage/health");
            });
        }
      } else {
        console.log("校验失败！", fields);
      }
    });
  },

  onReset() {
    $.loadEdit();
  },

  loadEdit() {
    getById(router.currentRoute.value.query.id).then((data) => {
      _$.requestParam = data;
      _$.fileList.push({
        name: _$.requestParam.healthFile,
        url: `${uploadServerUrl}${_$.requestParam.healthFile}`,
      });
    });
  },

  handleSizeChange(val) {
    _$.supplier.responseParam.pageSize = val;
    $.loadSuppliers();
  },

  handleCurrentChange(val) {
    _$.supplier.responseParam.pageNum = val;
    $.loadSuppliers();
  },

  handleSelectionChange(e) {
    _$.supplierSelected.length = 0;
    _$.supplierSelected.push(...e);
  },

  onExceed(files) {
    $refs[1].value.clearFiles();
    const file = files[0];
    file.uid = genFileId();
    $refs[1].value.handleStart(file);
  },

  onUploadSuccess(response) {
    _$.requestParam.healthFile = response.data;
  },

  clean() {
    _$.requestParam = {};
    _$.fileList.length = 0;
    $refs.length = 0;
  },
};

export const to = {};
